using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Net8.Identity.Server.Extensions;
using Net8.Identity.Server.Services;
using System.Security.Claims;
using OpenIddict.Abstractions;

namespace Net8.Identity.Server.Pages
{
    /// <summary>
    /// 登录页
    /// </summary>
    public class AuthenticateModel : PageModel
    {
        private readonly ApplicationDbContext _dbContext;
        public AuthenticateModel(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public string Email { get; set; } = "test1";

        public string Password { get; set; } = "123456";

        [BindProperty]
        public string ReturnUrl { get; set; }

        public string AuthStatus { get; set; } = "";

        public IActionResult OnGet(string returnUrl)
        {
            ReturnUrl = returnUrl;

            if (string.IsNullOrWhiteSpace(ReturnUrl))
                AuthStatus = "回调地址不存在，登录后将跳转到首页";
            return Page();
        }
        public async Task<IActionResult> OnPostAsync(string email, string password)
        {
            if (!await _dbContext.Users.AnyAsync(u => u.UserName == email || u.Email == email))
            {
                AuthStatus = "用户名不存在";
                return Page();
            }

            var user = await _dbContext.Users.Where(u => u.UserName == email || u.Email == email).FirstOrDefaultAsync();

            if (!PasswordHasher.VerifyHashedPassword(password, user.Password))
            {
                AuthStatus = "密码不正确";
                return Page();
            }

            var claims = new List<Claim>
            {
                new Claim(OpenIddictConstants.Claims.Subject, user.Id.ToString()),
                new Claim(OpenIddictConstants.Claims.Email, user.Email),
                new Claim(OpenIddictConstants.Claims.Name, user.UserName)
            };

            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var principal = new ClaimsPrincipal(identity);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

            if (!string.IsNullOrEmpty(ReturnUrl))
                return Redirect(ReturnUrl);
            
            AuthStatus = "认证通过";
            // 如果没有ReturnUrl，则重定向到首页
            return Redirect("/");
        }
    }
}